package com.ha.auto_skip.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;

import com.ha.auto_skip.App;
import com.ha.auto_skip.R;
import com.ha.auto_skip.bean.JumpBean;
import com.xinkao.skmvp.utils.Log2f;
import com.xinkao.skmvp.utils.MyToast;

import java.util.ArrayList;
import java.util.List;

public class SkipService extends AccessibilityService {
    /**
     * 当前activity
     */
    private String nowActivity = "";

    private String lastPack = "";

    private View mBarView;

    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {

        switch (accessibilityEvent.getEventType()) {
            case AccessibilityEvent.TYPE_WINDOWS_CHANGED:
            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
                if (TextUtils.isEmpty(nowActivity)) {
                    return;
                }
                AccessibilityNodeInfo rowNode = getRootInActiveWindow();
                if (rowNode != null) {
                    List<JumpBean> list = inPackage(String.valueOf(rowNode.getPackageName()), nowActivity);
                    if (list.size() > 0) {
                        recycle(list, rowNode, nowActivity);
                    }
                }
            }
            break;
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: {
                //获取当前窗口activity名
                ComponentName componentName = new ComponentName(
                        accessibilityEvent.getPackageName().toString(),
                        accessibilityEvent.getClassName().toString()
                );
                try {
                    nowActivity = getPackageManager().getActivityInfo(componentName, 0).name;
                } catch (Exception e) {
//                    e.printStackTrace();
                    nowActivity = "";
                }
            }
            default:
                break;
        }
    }

    public void recycle(List<JumpBean> list, AccessibilityNodeInfo info, String activityName) {
        if (info.getChildCount() == 0) {
            try {
                Log2f.w(String.valueOf(info.getText()));
                for (JumpBean bean : list) {
                    boolean skip;
                    if (bean.getFuzzy()) {
                        skip = String.valueOf(info.getText()).contains(bean.getKey());
                    } else {
                        skip = String.valueOf(info.getText()).equals(bean.getKey());
                    }
                    if (skip) {
//                        if (TextUtils.isEmpty(bean.getActivity_name())) {
//                            // 保存Activity名称
//                            bean.setActivity_name(activityName);
//                            App.getJumpListBean().saveAsJson();
//                        }

                        // 执行
                        skip(info);
                        // 标记点击
                        lastPack = bean.getPackage_name();
                        // 操作计次
                        bean.setTime(bean.getTime() + 1);
                        App.getJumpListBean().saveAsJson();
                    }
                }
            } catch (Exception e) {
                Log2f.e(e);
            }
        } else {
            for (int i = 0; i < info.getChildCount(); i++) {
                if (info.getChild(i) != null) {
                    recycle(list, info.getChild(i), activityName);
                }
            }
        }
    }

    private List<JumpBean> inPackage(String packName, String activityName) {
        List<JumpBean> list = new ArrayList<>();
        if (packName.equals(lastPack)) {
            return list;
        } else {
            lastPack = "";
        }
        for (JumpBean bean : getJumpBeanList()) {
            if (bean.getPackage_name().equals(packName)) {
//                if (TextUtils.isEmpty(bean.getActivity_name())
//                        || activityName.equals(bean.getActivity_name())) {
//                    list.add(bean);
//                }
                list.add(bean);
            }
        }
        return list;
    }

    private void skip(AccessibilityNodeInfo info) {
        Rect outBounds = new Rect();
        info.getBoundsInScreen(outBounds);
        int x = ((outBounds.right - outBounds.left) / 2) + outBounds.left;
        int y = ((outBounds.bottom - outBounds.top) / 2) + outBounds.top;
//        Log2f.i("标记位置：x:" + x + " y:" + y);
        gestureClick(x, y);
    }

    /**
     * 执行点击
     */
    private void gestureClick(int x, int y) {
        dispatchGesture(initGestureClick(x, y), new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
            }
        }, null);

    }

    // 初始化点击
    private GestureDescription initGestureClick(int x, int y) {
        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path path = new Path();
        path.moveTo(x, y);
        return builder.addStroke(new GestureDescription.StrokeDescription(path, 0, App.getClickDuration())).build();
    }

    private List<JumpBean> getJumpBeanList() {
        return App.getJumpListBean().getJumpList();
    }

    @SuppressLint("RtlHardcoded")
    private void showFloatingWindow() {
        if (Settings.canDrawOverlays(this) /*这个方法要求最低的sdk要23*/) {
            // 获取WindowManager服务
            WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
            // 新建悬浮窗控件
            mBarView = new View(getApplicationContext());
            mBarView.setBackgroundResource(R.drawable.bg_circle_bar);

            // 设置LayoutParam
            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                layoutParams.type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY;
            } else {
                layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            }

            layoutParams.format = PixelFormat.RGBA_8888;
            layoutParams.gravity = Gravity.CENTER | Gravity.BOTTOM;
            layoutParams.height = 5;
            layoutParams.width = 150;
            layoutParams.y = 4;

            layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;

            // 将悬浮窗控件添加到WindowManager
            windowManager.addView(mBarView, layoutParams);
        }
    }

    @Override
    public void onServiceConnected() {
        super.onServiceConnected();

        showFloatingWindow();
    }

    @Override
    public void onInterrupt() {

    }
}
